<script setup>
import { defineProps, ref } from 'vue'
import FileList from './FileList.vue'
import axios from 'axios';

import { dialogStatus } from '../store/store.js';
import { updateStatus } from '../store/status.js';
import { ElMessage } from 'element-plus';
// 读取存储的数据
let dialog = dialogStatus()
let status = updateStatus()

const data = defineProps({
    file: {
        type: Object,
        required: true
    },
    layer: {
        type: Number,
        default: 0
    }
})

var isOpen = ref(false);


const iconMap = {
    2: '/file.svg',
    1: '/fold.png'
}

function deleteFile(id) {
    // 发送删除请求, 以id为参数

    axios.delete(`http://localhost:8081/file`,
        {
            params: {
                id: id
            }
        }
    )
        .then(response => {
            if (response.data.data == true) {
                
                status.reshId = file.fatherId;
                status.needfresh = true;
                ElMessage.success('删除成功');
            } else {
                ElMessage.error('删除失败');
            }

        })
        .catch(error => {
            console.error('Error deleting file:', error);
        });



}

function showDialog(id, op) {
    dialog.show = true;
    dialog.op = op;
    //debugger;
    dialog.id = id;
    dialog.name = data.file.name;
    dialog.fatherId = data.file.fatherId; // 确保父级ID正确
}

</script>

<template>

    <div class="file-item">

        <div class="content-wrapper" :style="{ paddingLeft: data.layer * 20 + 'px' }">
            <img :src="iconMap[file.type]" class="file-logo">

            <span class="file-name">{{ file.name }}</span>
        </div>


        <div class="buttons">
            <el-button v-if="file.type == 1 & file.fileNum > 0" @click="isOpen = !isOpen">{{ isOpen ? "收起" :
                "展开" }}</el-button>

            <el-button v-if="file.type == 1" type="primary" @click="showDialog(file.id, 1)">新建文件</el-button>

            <el-button type="danger" @click="deleteFile(file.id)">删除</el-button>
            <el-button type="success" @click="showDialog(file.id, 2)">重命名</el-button>
        </div>
    </div>


    <FileList :fatherId="file.id" :layer="layer + 1" v-if="isOpen" />
</template>

<style scoped>
/* 美化文件项 */
.file-item {
    position: relative;
    display: flex;
    align-items: center;
    border-radius: 5px;

    height: 40px;
    background-color: #f9f9f9;
}

.file-logo {
    width: 24px;
    height: 24px;
    margin-right: 10px;
}

.file-name {
    font-weight: bold;
    color: #333;
    /* 下方加分割线 */
    border-bottom: 1px solid #f2f6fd;
}

.son-file-list {
    padding-left: 20px;
    /* 缩进子目录 */

}

.file-name {
    height: 100%;
    display: inline-flex;
    align-items: center;
}

/* 按钮靠右 */
.buttons {
    margin-left: auto;
    display: flex;
    align-items: center;
}
</style>
